import bgCImage from '@/assets/img/bgdevise.png';
import MyUpload from '@/components/MyUpload';
import { findByDataImageList, findByDataList, posterEdit } from '@/services/poster';
import { DropboxOutlined } from '@ant-design/icons';

import { ProCardTabsProps } from '@ant-design/pro-card/lib';
import {
  ProForm,
  ProFormColorPicker,
  ProFormDigit,
  ProFormList,
  ProFormSwitch,
  ProFormText,ProCard
} from '@ant-design/pro-components';
import { useMount } from 'ahooks';
import { Button, Card, Flex, Image, List, message } from 'antd';
import { MoveableManagerInterface, Renderer } from 'moveable';
import React, { ReactNode, useState } from 'react';
import Moveable from 'react-moveable';
import './index.css';
import ProList from '@ant-design/pro-list/lib';
import { useRequest } from 'ahooks';

interface RecordType {
  key: string;
  label: string;
  name: string;
  children: ReactNode;
  id: number;
  attr?: string;
  type: number;
}

interface PropsImage {
  id: number;
  x: number;
  y: number;
  w: number;
  h: number;
  radius: number;
  url: string;
  type: string;
  name: string;
  keyName: string;
  isRadius: boolean;
  remove: boolean;
  isWH: boolean;
  color: string;
  fontSize: number;
}

interface PropsImageType {
  id: number;
  posterId: number;
  imageId: number;
  url: string;
  type: any;
}

interface PropsForm {
  data: PropsImageType;
  posters: PropsImage[];
}

const Devise: React.FC = () => {
  const [form] = ProForm.useForm();
  const moveableRef = React.useRef<Moveable>(null);
  const [tab, setTab] = useState('0');
  const [tabPosition, setTabPosition] =
    useState<ProCardTabsProps['tabPosition']>('left');
  const [items, setItems] = useState<RecordType[]>();
  const [resItems, setResItems] = useState<RecordType[]>();
  const [item, setItem] = useState<RecordType>();
  const [strs, setStrs] = useState<string[]>();
  const [propImages, setPropImages] = useState<PropsImage[]>();
  const [propImage, setPropImage] = useState<PropsImage>();
  const [propPoster, setPropPoster] = useState<PropsImageType>();
  const [propIndex, setPropIndex] = useState<number>(-1);
  const [bgImage, setBgImage] = useState<string>(bgCImage);
  const [bgImageId, setBgImageId] = useState<number>(0);

const {data:imageList,run:imageRun}= useRequest(findByDataImageList)

  useMount(() => {
    findByDataList().then((res) => {
      setResItems(res);
      // @ts-ignore
      const mockData: RecordType[] = res.map(
        // @ts-ignore
        (_: RecordType, i: string) => ({
          key: i + '',
          label: _?.name,
          children: getChildrenBody(_, i, _?.attr),
          attr: _?.attr,
          id: _?.id,
          type: _?.type,
          icon: <DropboxOutlined />,
        }),
      );
      console.log(mockData);
      setItems(mockData);
    });
  });

  const targetRef = React.useRef<HTMLDivElement>(null);
  const spanRef = React.useRef<HTMLSpanElement>(null);
  function getResizeable(item: any) {
    let flag = false;
    switch (item) {
      case 'posterImage':
        flag = true;
        break;
      case 'qrcode':
        flag = true;
        break;
      case 'avatar':
        flag = true;
        break;

      default:
        flag = false;
        break;
    }
    return flag;
  }
  function getItemName(item: string) {
    let name = '';
    switch (item) {
      case 'posterImage':
        name = '海报';
        break;
      case 'qrcode':
        name = '维码  ';
        break;
      case 'avatar':
        name = '头像';
        break;
      case 'nickname':
        name = '昵称';
        break;
      case 'goodName':
        name = '商品';
        break;
      case 'price':
        name = '价格';
        break;
      case 'invite':
        name = '邀请  ';
        break;
      case 'authName':
        name = '认证';
        break;

      default:
        name = '';
        break;
    }
    return name;
  }

  function getChildrenBody(
    _: RecordType,
    index: any,
    attr: string | undefined,
  ) {

    return (

      <>
      <ProForm<PropsForm>
        form={form}
        initialValues={{
          data: {
            posterId: _.id,
            imageId: bgImageId,
            url: bgImage,
            type: _?.type,
          },
          posters: propImages,
        }}
        onChange={(values: any) => {
          console.log(values);
          if (values.posters) {
            moveableRef.current?.destroy();
            setPropImages(values.posters);
          }
        }}
        onFinish={async (value) => {
          return new Promise((resolve, reject) => {
            console.log(value);
            let values = value?.posters.filter((item) => item.remove === false);
            // @ts-ignore
            if (value.data.posterId > 0 && value.data.imageId > 0) {
              // @ts-ignore
              let param = {
                data: value.data,
                posters: values,
              };
              posterEdit(param)
                .then((res) => {
                  resolve(true);
                  message.success('操作成功');
                  form.resetFields();
                })
                .catch((e) => {
                  reject(false);
                });
            } else {
              message.error('请先保存海报');

              reject(false);
            }
          });
        }}
      >
        <ProFormText name={['data', 'id']} label={'名称'} hidden={true} />
        <ProFormText name={['data', 'posterId']} label={'名称'} hidden={true} />
        <ProFormText name={['data', 'type']} label={'名称'} hidden={true} />
        <ProFormText name={['data', 'imageId']} label={'名称'} hidden={true} />
        <ProFormText name={['data', 'url']} label={'名称'} hidden={true} />
        <MyUpload
          type={6}
          height="100px"
          id={bgImageId}
          url={bgImage}
          onChange={(imageId, url) => {
            console.log('onChange', imageId);
            // @ts-ignore
            setBgImageId(imageId);
            setBgImage(url);
            form.setFieldValue(['data', 'imageId'], imageId);
          }}
        />
        <ProFormList
          name="posters"
          copyIconProps={false}
          deleteIconProps={false}
          creatorButtonProps={false}
        >
          {(
            // 当前行的基本信息 {name: number; key: number}
            meta,
            // 当前的行号
            index,
            /**
             * action
             * @name 用于操作行的一些快捷方法
             * @example 给第二行增加数据 action.add?.({},1);
             * @example 删除第二行 action.remove?.(1);
             * @example 从 1 移到 2: action.move?.(2,1);
             * @example 获取当前行的数据: action.getCurrentRowData() -> {id:"xxx",name:'123',age:18}
             * @example 设置当前行的数据: {id:"123",name:'123'} -> action.setCurrentRowData({name:'xxx'}) -> {id:"123",name:'xxx'}
             * @example 清空当前行的数据：{id:"123",name:'123'} -> action.setCurrentRowData({name:undefined}) -> {id:"123"}
             */
            action,
            // 总行数
            count,
          ) => {
            return (
              <ProForm.Group>
                <ProFormText
                  name="keyName"
                  disabled={true}
                  label={'名称'}
                  width={'120px'}
                  fieldProps={{
                    onChange: (e: any) => {},
                  }}
                />
                <ProFormDigit
                  onChange={(x: any) => {
                    if (propImages) {
                      propImages[index].x = x;
                    }
                    setPropImages(propImages);
                    moveableRef.current?.setState({
                      targets: propImages,
                    });
                    return x;
                  }}
                  name="x"
                  label="X"
                  width={'120px'}
                  min={0}
                  max={750}
                  defaultValue={0}
                />
                <ProFormDigit
                  onChange={(y: any) => {
                    if (propImages) {
                      propImages[index].y = y;
                    }

                    setPropImages(propImages);

                    return y;
                  }}
                  name="y"
                  label="Y"
                  width={'120px'}
                  min={0}
                  max={1334}
                  defaultValue={0}
                />
                <ProFormDigit
                  onChange={(fontSize: any) => {
                    if (propImages) {
                      propImages[index].fontSize = fontSize;
                    }
                    setPropImages(propImages);
                    return fontSize;
                  }}
                  name="fontSize"
                  label="大小"
                  width={'80px'}
                  min={0}
                  max={100}
                  defaultValue={0}
                />
                <ProFormColorPicker
                  label={'颜色'}
                  fieldProps={{
                    onChange: (color: any) => {
                      console.log('color', color);
                    },
                  }}
                  onMetaChange={(color: any) => {
                    console.log('color', color.hex);
                  }}
                />
                <ProFormDigit
                  onChange={(w: any) => {
                    if (propImages) {
                      propImages[index].w = w;
                    }
                    setPropImages(propImages);
                  }}
                  name="w"
                  label="W"
                  width={'80px'}
                  min={0}
                  max={750}
                  defaultValue={0}
                />
                <ProFormDigit
                  onChange={(h: any) => {
                    if (propImages) {
                      propImages[index].h = h;
                    }
                    setPropImages(propImages);
                  }}
                  name="h"
                  label="H"
                  width={'80px'}
                  min={0}
                  max={1334}
                  defaultValue={0}
                />

                <ProFormSwitch name={'remove'} />
              </ProForm.Group>
            );
          }}
        </ProFormList>
      </ProForm>




      </>
    );
  }

  // 重新初始化Moveable实例的方法
  const restartMoveable = () => {
    if (moveableRef.current) {
      moveableRef.current.componentDidUpdate();

      //  moveableRef.current.destroy(); // 销毁当前的Moveable实例
      moveableRef.current = new Moveable(moveableRef.current, {
        draggable: true,
        resizable: true,
        throttleDrag: 0,
        throttleResize: 0,
      });
    }
  };

  const defaultPropImage: PropsImage = {
    id: 0,
    x: 0,
    y: 0,
    w: 0,
    h: 0,
    radius: 0,
    url: '',
    type: 'text',
    name: '',
    keyName: '',
    isRadius: false,
    isWH: false,
    remove: false,
    color: '',
    fontSize: 12,
  };
  const getEdit = (index: number) => {
    let prop = propImages?.at(index) || defaultPropImage;
    return {
      name: 'editable',
      props: [],
      events: [],
      render(moveable: MoveableManagerInterface<any, any>, React: Renderer) {
        const rect = moveable.getRect();
        const { pos2 } = moveable.state;

        // Add key (required)
        // Add class prefix moveable-(required)
        const EditableViewer = moveable.useCSS(
          'div',
          `
       {
           position: absolute;
           left: 0px;
           top: 0px;
           will-change: transform;
           transform-origin: 0px 0px;
       }
       .custom-button {
           width: 20px;
           height: 20px;
           background: #4af;
           border-radius: 4px;
           appearance: none;
           border: 0;
           color: white;
           font-weight: bold;
       }
           `,
        );
        // @ts-ignore
        return (
          <EditableViewer
            key={'editable-viewer'}
            className={'moveable-editable'}
            style={{
              transform: `translate(${pos2[0]}px, ${pos2[1]}px) rotate(${rect.rotation}deg) translate(10px)`,
            }}
          >
            {!getResizeable(prop.keyName) ? (
              <>
                <button
                  className="custom-button"
                  onClick={() => {
                    //  alert('+');
                    propImages![index].fontSize = prop.fontSize + 2;
                    setPropImages(propImages);
                  }}
                >
                  +
                </button>
                <button
                  className="custom-button"
                  onClick={() => {
                    //  alert('-');
                    console.log('prop', moveable);
                    propImages![index].fontSize = prop.fontSize - 2;
                    setPropImages(propImages);
                  }}
                >
                  -
                </button>
              </>
            ) : (
              <></>
            )}
          </EditableViewer>
        );
      },
    } as const;
  };

  // @ts-ignore
  return (
    <>
      {' '}
      <ProCard split="vertical">
        <ProCard
          title="左侧详情"
          colSpan="390px"
          /*      extra={
                    <Button
                      type="primary"
                      onClick={() => {
                        console.log('propImages', propImages, bgImageId, item);
                        const data = {
                          posterId: item?.id,
                          imageId: bgImageId,
                          type: item?.type,
                        };
                        // @ts-ignore
                        let values = propImages.filter((item) => item.remove === false);
                        // @ts-ignore
                        if (item.id > 0 && bgImageId > 0) {
                          // @ts-ignore
                          let param = {
                            data: data,
                            posters: Object.values(values),
                          };
                          posterEdit(param).then((res) => {
                            console.log(res);
                          });
                        }
                      }}
                    >
                      保存
                    </Button>
                  }*/
        >
          <div className="container">
            <span ref={spanRef}>Position</span>
            <div
              className="preview"
              style={{
                position: 'relative',
                width: '750px',
                height: '1334px',
                transform: 'scale(0.47123)',
                transformOrigin: 'top left',
                backgroundImage: `url(${bgImage})`,
                border: '1px solid #000',
              }}
            >
              {strs?.map((item, index) => {
                let prop = propImages?.at(index);
                // @ts-ignore
                return !prop?.remove ? (
                  <div
                    className={'target ' + item}
                    onClick={() => {
                      console.log('click', index);
                      let prop = propImages?.at(index);
                      setPropIndex(index);
                      setPropImage(prop);
                    }}
                    style={{
                      top: '0px',
                      left: '0px',
                      position: 'absolute',
                      fontSize: propImages?.at(index)?.fontSize + 'px',
                      zIndex: { index } + '',
                    }}
                  >
                    {item}
                  </div>
                ) : null;
              })}
            </div>
            {strs?.map((item, index) => {
              let prop = propImages?.at(index);
              return !prop?.remove ? (
                <Moveable
                  ref={moveableRef}
                  target={'.' + item}
                  draggable={true}
                  snappable={true}
                  origin={false}
                  props={{
                    editable: true,
                  }}
                  resizable={getResizeable(item)}
                  snapContainer=".preview"
                  selectByClick={true}
                  selectFromInside={true}
                  bounds={{
                    left: 0,
                    top: 0,
                    zoom: index + 1,
                  }}
                  snapGap={true}
                  snapDirections={{
                    top: true,
                    left: true,
                    bottom: true,
                    right: true,
                    center: true,
                    middle: true,
                  }}
                  elementSnapDirections={{
                    top: true,
                    left: true,
                    bottom: true,
                    right: true,
                    center: true,
                    middle: true,
                  }}
                  onResize={(e) => {
                    let prop = propImages?.at(index);
                    setPropIndex(index);
                    setPropImage(prop);
                    let w = e.width;
                    let h = e.height;

                    if (propImages) {
                      propImages[index].w = w;
                      propImages[index].h = h;
                    }
                    setPropImages(propImages!);

                    e.target.style.width = `${e.width}px`;

                    e.target.style.height = `${e.height}px`;
                    e.target.style.transform = e.drag.transform;
                    if (prop) {
                      e.target.style.fontSize = `${prop.fontSize}px`;
                    }
                    form.setFieldValue('posters', propImages);
                  }}
                  onDrag={(e) => {
                    let prop = propImages?.at(index);
                    setPropIndex(index);
                    setPropImage(prop);
                    e.target.style.transform = e.transform;
                    console.log(e);

                    let x = e.translate[0];
                    let y = e.translate[1];
                    let w = e.width;
                    let h = e.height;
                    if (propImages) {
                      propImages[index].w = w;

                      propImages[index].h = h;
                      propImages[index].x = x;
                      propImages[index].y = y;
                    }
                    setPropImages(propImages!);
                    form.setFieldValue('posters', propImages);
                    spanRef.current!.innerHTML = `${x} x ${y}`;
                    if (prop) {
                      e.target.style.fontSize = `${prop.fontSize}px`;
                    }
                    console.log(propImages, propImage, propIndex);
                  }}
                  onSelectEnd={(e: any) => {
                    let prop = propImages?.at(index);
                    console.log(e);
                    if (prop) {
                      e.target.style.fontSize = `${prop.fontSize}px`;
                    }
                  }}
                />
              ) : null;
            })}
          </div>
        </ProCard>
        <ProCard
          title="海报管理"
          tabs={{
            tabPosition,
            activeKey: tab,
            items: items,
            onChange: (key) => {
              form.resetFields();
              restartMoveable();
              setPropImages([]);
              setTab(key);
              console.log(key);
              let find = items?.find((item) => item.key === key);
              console.log(find);
              imageRun(find?.id);
              setItem(find);
              if (find?.attr) {
                let split = find?.attr.split(',');
                setStrs(split);
                if (Array.isArray(split)) {
                  // @ts-ignore
                  // @ts-ignore
                  let map = split.map((item, index) => ({
                    ...defaultPropImage,
                    // id: index,
                    // @ts-ignore
                    type: getResizeable(item),
                    keyName: item,
                  }));
                  form.setFieldValue('posters', map);
                  setPropImages(
                    // @ts-ignore
                    map,
                  );
                }
              }
            },
          }}
          actions={
            <div style={{ width: '100%' }}>
              <Flex wrap  gap={"small"}>
                {imageList?.map((item) => (
                  <div style={{ width: 100 ,backgroundColor: '#eee',borderRadius: 5,overflow: 'hidden'}}>
                    <img style={{ width: '100%' }} alt="example" src={item?.url} />
                    <div style={{ padding: 10, textAlign: 'center' }}>
                      <Button
                        type="primary"
                        danger
                        onClick={() => {
                        //.  imageRun(item?.id);
                        }}
                      >
                        删除
                      </Button>
                    </div>
                  </div>
                ))}
              </Flex>
            </div>
          }
        />
      </ProCard>
    </>
  );
};
export default Devise;
